#!/bin/bash

set -eux

CUR_FOLDER=$(basename $(pwd))
if [ "$CUR_FOLDER" != infrastructure ]; then
  echo "Error, must be in the infrastructure folder to run this script."
  exit 1
fi

export VERSION=$(sed 's/.*=\s*//' ../game-core/src/main/resources/META-INF/triplea/product.properties)

export CRT_FILE="triplea-nginx-vagrant.crt"

function main() {
  symlinkNginxCert
  buildJars
  buildMigrations

  ansible-playbook -D -v \
      "$@" \
      ansible/site.yml \
      -i ansible/inventory/vagrant
  # Update certs to pick up new or updated certs from nginx
  sudo update-ca-certificates -f
}

function symlinkNginxCert() {
  local link="/usr/local/share/ca-certificates/${CRT_FILE}"
  if [ ! -L "$link" ]; then
    sudo ln -s "$(pwd)/.vagrant/${CRT_FILE}" "$link"
  fi
}

function buildJars() {
  (
    cd ../
    ./gradlew :http-server:shadowJar :game-headless:shadowJar
    
    local targetFolder="./infrastructure/ansible/roles"
    mkdir -p "${targetFolder}/bot/files/" "${targetFolder}/http_server/files/"
    cp "game-headless/build/libs/triplea-game-headless-${VERSION}.jar" "${targetFolder}/bot/files/"
    cp "http-server/build/libs/triplea-http-server-${VERSION}.jar" "${targetFolder}/http_server/files/"
  ) 
}

function buildMigrations() {
  local targetFolder=./ansible/roles/flyway/files/
  local zipFile=migrations.zip
  if [ ! -e $targetFolder/$zipFile ]; then
    (
      cd ../lobby-db
      if [ ! -e build/distributions/$zipFile ]; then
        ../gradlew release 
      fi
      cd ../infrastructure
      mkdir -p $targetFolder
      cp ../lobby-db/build/distributions/$zipFile $targetFolder
    )
  fi
}

main "$@"

